/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

-function (global, top) { "use strict";
    // 控制台
    global.ym2App.controller("ym2.ctrl.site.login", ["$scope", "$http", "ym2", "layui", "$timeout", function ($scope, $http, ym2, layui, $timeout) {
        var httpSuccessCode = ym2.getHttpSuccessCode();
        var httpFailureCode = ym2.getHttpFailureCode();

        // 初始化SCOPE
        $scope.initScope = function () {
            $scope.errorMessage = '';
            $scope.username = '';
            $scope.password = '';

            $scope.logining = false;
        };
        $scope.initScope();
        // layui-input清除事件触发change
        layui.form.on('input-affix(clear)', function(data){
            $timeout(function () {
                layui.jquery(data.elem).trigger("change");
            });
        });
        // 表单校验
        $scope.formValidate = function () {
            if (!$scope.username) {
                $scope.errorMessage = "请填写账号";
                return false;
            }
            if (!$scope.password) {
                $scope.errorMessage = "请填写密码";
                return false;
            }

            $scope.errorMessage = "";
            return true;
        };
        // 登录提交
        $scope.loginSubmit = function (e) {
            if (!$scope.formValidate()) {
                return;
            }

            // 发起请求
            $scope.logining = true;
            $http.post("/site/login", {
                username: $scope.username,
                password_hash: $scope.password,
            }).then(function (result) {
                $scope.logining = false;

                var data = result.data;
                switch (data.code) {
                    case httpSuccessCode:
                        global.location.href = data.data;
                        break;
                    case httpFailureCode:
                    default:
                        $scope.errorMessage = data.msg || "未知错误!";
                }
            }, function (error) {
                console.log(error);
                $scope.logining = false;
                $scope.errorMessage = error.data || '请求出错,请打开浏览器控制台查看!';
            });
        };

    }]);
}(window, top);